<?php

namespace App\Imports;

use App\Models\HospitalImportBigchild;
use App\Models\HospitalImportCheckup;
use App\Models\HospitalImportChild;
use App\Models\HospitalImportPregn;
use App\Models\HospitalUploadData;
use App\Models\ImportFamily;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Arr;

class HospitalImport implements ToModel, WithHeadingRow
{
    private $modelClass;
    private $hospitalUploadData;
    public function __construct(HospitalUploadData $hospitalUploadData)
    {
        $this->hospitalUploadData = $hospitalUploadData;
    }
    private $headerRowNumber = 1;
    public function headingRow()
    {
        return $this->headerRowNumber;
    }
    public function model(array $row)
    {
        // 首次处理表头行，获取表头名称数组
        if ($this->modelClass === null) {
            $this->modelClass = $this->determineModel($row);
            if (!$this->modelClass) {
                throw new \Exception('无法根据表头确定对应的插入数据表',400);
            }
            $model = app($this->modelClass);
            $config = config('hospital_import_field.'.$model->getTable());

            if($config['type']!=4) {
                //清空关联关系，重新匹配（剔除迁出用户）
                ImportFamily::query()
                    ->where('hospital_id', $this->hospitalUploadData->hospital_id)
                    ->where('type', $config['type'])
                    ->delete();
            }
            $model->query()
                ->where('hospital_id',$this->hospitalUploadData->hospital_id)
                ->update(['status' => 0]);
            DB::commit();

        }

         //根据确定好的模型类创建模型实例，并将当前行数据插入到对应数据表
        $model = app($this->modelClass);
        $data = [];
        $config = config('hospital_import_field.'.$model->getTable());
        $fields = $config['fields'];
        $uniques = $config['uniques'];
        foreach ($row as $header => $value) {
            if(!isset($fields[$header]))
                continue;
            $field = $fields[$header];
            $value = str_replace('*','',$value);
            if($value == "")
                continue;
            //$model->$field = $value;
            $data[$field] = $value;
        }
        $data['hospital_id'] = $this->hospitalUploadData->hospital_id;
        $data['status'] = 1;

        $uniquesArr = Arr::only($data,$uniques);

        $request = $model->updateOrCreate($uniquesArr,$data);
        DB::commit();
        $queue = $config['queue_name'];
        $queue::dispatch($request);
        return null;
    }

    private function determineModel(array $headers)
    {
        // 根据表头中的特定字段名称判断插入哪张表，以下是简单示例，可按需扩展修改逻辑
        if (isset($headers['母亲姓名']) && isset($headers['母亲身份证号'])) {
            $this->hospitalUploadData->type = 3;
            $this->hospitalUploadData->save();
            return HospitalImportChild::class;
        } elseif (isset($headers['体检日期']) && isset($headers['实足年龄_岁'])) {
            $this->hospitalUploadData->type = 1;
            $this->hospitalUploadData->save();
            return HospitalImportCheckup::class;
        }elseif (isset($headers['产妇条码']) && isset($headers['产妇姓名'])) {
            $this->hospitalUploadData->type = 2;
            $this->hospitalUploadData->save();
            return HospitalImportPregn::class;
        }elseif (isset($headers['受种者编码']) && isset($headers['受种者姓名'])) {
            $this->hospitalUploadData->type = 4;
            $this->hospitalUploadData->save();
            return HospitalImportBigchild::class;
        }
        return null;
    }

}
